import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { products, inventory, orders, customers } from '@/lib/schema';
import { desc, eq, lt, and, gte } from 'drizzle-orm';

export async function GET() {
  try {
    // 获取产品数量
    const productsCount = await db
      .select({ count: products.id })
      .from(products)
      .then(rows => rows.length);

    // 获取库存总商品种类数量
    const inventoryCount = await db
      .select({ count: inventory.id })
      .from(inventory)
      .then(rows => rows.length);

    // 获取订单数量
    const ordersCount = await db
      .select({ count: orders.id })
      .from(orders)
      .then(rows => rows.length);

    // 获取客户数量
    const customersCount = await db
      .select({ count: customers.id })
      .from(customers)
      .then(rows => rows.length);

    // 获取最近5个订单
    const recentOrders = await db
      .select({
        id: orders.id,
        orderNumber: orders.id,
        status: orders.status,
        totalAmount: orders.totalAmount
      })
      .from(orders)
      .orderBy(desc(orders.createdAt))
      .limit(5);

    // 获取低库存商品（库存 <= 10）
    const lowStockItems = await db
      .select({
        id: products.id,
        name: products.name,
        quantity: inventory.quantity
      })
      .from(inventory)
      .innerJoin(products, eq(inventory.productId, products.id))
      .where(lt(inventory.quantity, 10))
      .orderBy(inventory.quantity)
      .limit(5);

    return NextResponse.json({
      productsCount,
      inventoryCount,
      ordersCount,
      customersCount,
      recentOrders,
      lowStockItems
    });

  } catch (error) {
    console.error('获取仪表板统计数据失败:', error);
    return NextResponse.json(
      { error: '获取统计数据失败' },
      { status: 500 }
    );
  }
}